package com.edu.internship.glabal.response;

import com.edu.internship.glabal.constants.Result;
import com.edu.internship.util.JsonUtils;
import com.edu.internship.util.Tools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * code is far away from bug with the animal protecting
 *
 * @author lishiquan
 * @description 全局返回对象处理
 * @date 2022-07-29
 */
@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalDefaultResponseHandler implements ResponseBodyAdvice<Object>  {

    private static final String VOID = "void";

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> converterType,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        String methodParameterName = methodParameter.getParameterType().getName();
        if (StringUtils.equals(VOID, methodParameterName)) {
            return Result.success();
        }
        if (Tools.equals(Result.class.getName(), methodParameterName)) {
            return body;
        }
        if (Tools.equals(String.class.getName(), methodParameterName)) {
            serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return JsonUtils.getInstance().convertToStr(Result.success(body.toString()));
        }
        if (Tools.equals(Long.class.getName(), methodParameterName)) {
            return Result.success(String.valueOf(body));
        }
        if (Tools.equals(ResponseEntity.class.getName(), methodParameterName)) {
            return body;
        }
        return Result.success(body);
    }
}
